package com.yupi.yuoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.content.ContentQueryRequest;
import com.yupi.yuoj.model.entity.Content;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.ContentVO;
import com.yupi.yuoj.model.vo.UserVO;
import com.yupi.yuoj.service.ContentService;
import com.yupi.yuoj.service.UserService;
import com.yupi.yuoj.mapper.ContentMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author admin
* @description 针对表【content(学习内容表)】的数据库操作Service实现
* @createDate 2025-11-01 21:28:58
*/
@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content>
    implements ContentService{

    @Resource
    private UserService userService;

    @Override
    public void validContent(Content content, boolean add) {
        if (content == null) {
            throw new RuntimeException(ErrorCode.PARAMS_ERROR.getMessage());
        }
        String title = content.getTitle();
        String content_text = content.getContent();
        String type = content.getType();
        String category = content.getCategory();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(ObjectUtils.anyNull(title, content_text, type, category), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new RuntimeException(ErrorCode.PARAMS_ERROR.getMessage());
        }
        if (StringUtils.isNotBlank(content_text) && content_text.length() > 8192) {
            throw new RuntimeException(ErrorCode.PARAMS_ERROR.getMessage());
        }
    }

    @Override
    public ContentVO getContentVO(Content content, HttpServletRequest request) {
        ContentVO contentVO = ContentVO.objToVo(content);
        // 1. 关联查询用户信息
        Long userId = content.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        contentVO.setUser(userVO);
        return contentVO;
    }

    @Override
    public QueryWrapper<Content> getQueryWrapper(ContentQueryRequest contentQueryRequest) {
        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
        if (contentQueryRequest == null) {
            return queryWrapper;
        }
        
        Long id = contentQueryRequest.getId();
        String searchText = contentQueryRequest.getSearchText();
        String title = contentQueryRequest.getTitle();
        String type = contentQueryRequest.getType();
        String category = contentQueryRequest.getCategory();
        List<String> tags = contentQueryRequest.getTags();
        List<String> orTags = contentQueryRequest.getOrTags();
        Integer difficulty = contentQueryRequest.getDifficulty();
        Integer status = contentQueryRequest.getStatus();
        Long userId = contentQueryRequest.getUserId();
        Long collectionUserId = contentQueryRequest.getCollectionUserId();
        Integer isFeatured = contentQueryRequest.getIsFeatured();
        String sortField = contentQueryRequest.getSortField();
        String sortOrder = contentQueryRequest.getSortOrder();
        
        // 拼接查询条件
        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.eq(StringUtils.isNotBlank(type), "content_type", type);
        queryWrapper.eq(StringUtils.isNotBlank(category), "category", category);
        queryWrapper.eq(difficulty != null && difficulty > 0, "difficulty", difficulty);
        queryWrapper.eq(status != null, "status", status);
        queryWrapper.eq(userId != null && userId > 0, "user_id", userId);
        queryWrapper.eq(isFeatured != null, "is_featured", isFeatured);
        
        // 搜索词匹配标题或内容
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content_text", searchText));
        }
        
        // 标签查询（AND关系）
        if (CollectionUtils.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        
        // 标签查询（OR关系）
        if (CollectionUtils.isNotEmpty(orTags)) {
            queryWrapper.and(qw -> {
                for (int i = 0; i < orTags.size(); i++) {
                    if (i == 0) {
                        qw.like("tags", "\"" + orTags.get(i) + "\"");
                    } else {
                        qw.or().like("tags", "\"" + orTags.get(i) + "\"");
                    }
                }
            });
        }
        
        // 收藏用户查询
        if (collectionUserId != null && collectionUserId > 0) {
            queryWrapper.inSql("id", "SELECT content_id FROM content_collection WHERE user_id = " + collectionUserId);
        }
        
        // 排序规则
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder != null && sortOrder.equals("ascend"), sortField);
        
        return queryWrapper;
    }

    @Override
    public Page<ContentVO> getContentVOPage(Page<Content> contentPage, HttpServletRequest request) {
        List<Content> contentList = contentPage.getRecords();
        Page<ContentVO> contentVOPage = new Page<>(contentPage.getCurrent(), contentPage.getSize(), contentPage.getTotal());
        if (contentList.isEmpty()) {
            return contentVOPage;
        }
        
        // 填充信息
        List<ContentVO> contentVOList = contentList.stream()
                .map(content -> getContentVO(content, request))
                .collect(Collectors.toList());
        
        contentVOPage.setRecords(contentVOList);
        return contentVOPage;
    }

}




